package com.dxtx.test;

import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.ViewTreeObserver;
import android.widget.TextView;

/**
 * Created by user on 2017/4/26.
 */
public class AutoSingleLineTextView extends TextView {
    private float superTextSize;

    public AutoSingleLineTextView(Context context) {
        super(context);
    }

    public AutoSingleLineTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        superTextSize = getTextSize();
        Log.d("px", superTextSize + "-->superTextSize");
    }

    @Override
    public void setText(final CharSequence text, BufferType type) {

        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                getViewTreeObserver().removeGlobalOnLayoutListener(this);
                adjustByText(text.toString());
            }
        });
        super.setText(text, type);
    }

    private void adjustByText(String text) {
        Paint paint = getPaint();
        float textSize = getTextSize();
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        int width = bounds.width();
        int height = bounds.height();

        Log.d("px", textSize + ",width=" + width + ",height=" + height);

        float w = getWidth() - getPaddingLeft() - getPaddingRight();
        if (width > w) {
            float size = w / width * textSize * 0.95f;
            Log.d("px", size + "-->size");
            //按像素设置字体
            super.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
        } else {
            super.setTextSize(TypedValue.COMPLEX_UNIT_PX, superTextSize);
        }
    }

    @Override
    public void setTextSize(int unit, float size) {
        super.setTextSize(unit, size);
        superTextSize = getTextSize();
        Log.d("px", superTextSize + "-->superTextSize");
    }
}
